package com.ljz.untils;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class DBUtils2 {

    private DBUtils2() {}
    private static Properties properties;

    static {
        try {
            FileInputStream  fis = new FileInputStream("src/main/resources/jdbc.properties");
            properties = new Properties();
            properties.load(fis);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn() {
//        DBUtils2 dbUtils2 = new DBUtils2();

        try {
            Class.forName(properties.getProperty("driver"));
            Connection conn = DriverManager.getConnection(properties.getProperty("url"),
                    properties.getProperty("username"), properties.getProperty("password"));
            return conn;
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static int exceUpdate(String sql, List<Object> list){
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = getConn();
            if (conn != null) {
                ps = conn.prepareStatement(sql);
            }
            for (int i = 0; i < list.size(); i++) {
                ps.setObject(i+1,list.get(i));
            }
            int i = ps.executeUpdate();
            return i;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(null,ps,conn);
        }
    }
    public static void closeAll(ResultSet rs,PreparedStatement ps,Connection conn){
        try {
            if (rs!=null)
                rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (ps!=null)
                ps.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (conn!=null)
                conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
